<template>
    <div class="book-out-container">
        <div>
            <div class="text-title ft-c-g">书籍 · 漂出</div>
            <div class="ft-c-666 txt-a-c mb-15 ft-s-12">支持扫码或手动录入，退出后可继续补充未完成记录</div>
        </div>
        <div v-for="(book, idx) in books" :key="idx" class="book-item">
            <div class="flex justify-between items-center mb-15 bok-title-row">
                <span class="ft-c-gn">第{{ idx + 1 }}本</span>
                <van-button type="danger" size="mini"
                            plain
                            @click="removeBook(idx)"
                            class="remove-button">移除
                </van-button>
            </div>
            <van-field v-model="book.isbn" label="ISBN码" placeholder="请输入ISBN码" required>
                <template #button>
                    <van-button size="mini" type="success" @click="startScan(book)">扫码填入</van-button>
                </template>
            </van-field>
            <van-field v-model="book.title" label="书名" placeholder="请输入书名" required/>
        </div>
        <van-button block type="primary" plain @click="addBook" class="add-button">
            <van-icon name="plus"/>
            继续添加
        </van-button>
        <!-- 在库书籍确认提示 -->
        <div class="book-confirm-tip">
            <van-icon name="warning-o" color="#ff6b35" />
            <span class="tip-text">如系统提示未找到在库书籍，请检查扫码识别的书名是否正确，或与工作人员确认在库书籍的录入名称</span>
        </div>
        <van-button block type="success" @click="onBatchBorrow" class="submit-button">提交</van-button>
        <!--返回按钮-->
        <van-button
            icon="wap-home-o"
            class="fixed-back-button"
            @click="goBack"
        />
        <BarcodeScanner
            v-if="scanning"
            @scan-success="handleScanSuccess"
            @scan-error="handleScanError"
            @scan-cancel="handleScanCancel"
        />
    </div>
</template>

<script setup lang="ts">
import {ref, watch} from 'vue';
import {showDialog, showFailToast, showToast} from 'vant';
//@ts-ignore
import {bookApi} from "@/api/lbBook.ts";
import BarcodeScanner from './scan/ScanBar.vue';

// 初始化书籍列表，从 localStorage 恢复进度，如果没有数据则默认添加一个空的书籍对象
const books = ref(JSON.parse(localStorage.getItem('bookOutFrom') || '[]'));
if (books.value.length === 0) {
    books.value.push({isbn: '', publisher: '', publishDate: '', title: '', pages: ''});
}

// 添加一本书
const addBook = () => {
    books.value.push({isbn: '', publisher: '', publishDate: '', title: '', pages: ''});
};

// 移除一本书
const removeBook = (idx: number) => {
    books.value.splice(idx, 1);
};

// 检查书名长度并确认
const checkBookTitleLength = async () => {
    for (let i = 0; i < books.value.length; i++) {
        const book = books.value[i];
        if (book.title && book.title.length > 20) {
            try {
                await showDialog({
                    title: '书名确认',
                    message: `第${i + 1}本书名是：${book.title}，确认正确吗？\n\n确认正确则直接提交入库。`,
                    messageAlign: 'left',
                    confirmButtonText: '确认正确',
                    cancelButtonText: '重新编辑',
                    showCancelButton: true,
                    beforeClose: (action) => {
                        if (action === 'confirm') {
                            return true;
                        }
                        return true;
                    }
                }).then(() => {
                    // 用户确认正确，继续
                    return true;
                }).catch(() => {
                    // 用户选择重新编辑，抛出异常中断流程
                    throw new Error('用户选择重新编辑');
                });
            } catch (error) {
                return false; // 中断提交流程
            }
        }
    }
    return true; // 所有检查通过
};

// 提交批量漂出
const onBatchBorrow = async () => {
    if (books.value.length == 0) {
        //跳转到首页
        showFailToast('请添加书籍信息');
        return
    }
    //检查每本书的书名跟isbn属性是否有值
    for (let i = 0; i < books.value.length; i++) {
        if (!books.value[i].title || !books.value[i].isbn) {
            showFailToast('请补全书第' + (i + 1) + '本书信息');
            return
        }
    }
    //检测是否有重复书籍
    for (let i = 0; i < books.value.length; i++) {
        for (let j = i + 1; j < books.value.length; j++) {
            if (books.value[i].title === books.value[j].title) {
                showToast('存在重复书籍，请检查');
                return;
            }
        }
    }
    
    // 检查书名长度
    const titleCheckPassed = await checkBookTitleLength();
    if (!titleCheckPassed) {
        return; // 用户选择重新编辑，中断提交流程
    }
    
    let params = {
        books: books.value
    }
    bookApi.bookOutApply(params).then((res) => {
        console.log("nowInfo", res);
        //跳转到首页
        showDialog({
            message: '提交漂出成功，请等待审核',
        }).then(() => {
            books.value = [{isbn: '', publisher: '', publishDate: '', title: '', pages: ''}];
            //清除缓存
            localStorage.deleteItem('bookInFrom')
            goBack()
        });
    });
};

// 保存进度到 localStorage
const saveProgress = () => {
    localStorage.setItem('bookOutFrom', JSON.stringify(books.value));
};

// 监听书籍列表变化，自动保存进度
watch(
    () => books.value,
    (newVal) => {
        console.log("books", newVal)
        saveProgress();
    },
    {deep: true}
);

// 新增返回按钮功能
const goBack = () => {
    window.history.back();
};

//扫描相关
const scanning = ref(false);
const result = ref('');
const scanBook = ref<any>({});
//开始扫描
const startScan = (book: any) => {
    scanBook.value = book;
    scanning.value = true;

};
//扫描成功
const handleScanSuccess = (isbn: string) => {
    result.value = isbn;
    scanning.value = false;
    //获取isbn书籍信息
    bookApi.isbnSearch({isbn: isbn}).then((res) => {
        //判断books中是否有isbn一直的书
        if (books.value.find((item: any) => item.isbn === isbn)) {
            showToast('已存在该isbn书籍');
            return;
        }
        scanBook.value.isbn = res.isbn;
        scanBook.value.title = res.title
        scanBook.value.publisher = res.publisher
        scanBook.value.pubDate = res.pubDate
        scanBook.value.pageCount = res.pageCount
    });
};
//扫描失败
const handleScanError = (error: Error) => {
    console.error('扫描失败:', error);
    scanning.value = false;
};
//扫描取消
const handleScanCancel = () => {
    scanning.value = false;
};
</script>

<style scoped>
.book-out-container {
    padding: 20px;
    min-height: 80vh;
}

.book-item {
    margin-bottom: 20px;
    position: relative;
}

.text-title {
    text-align: center;
    font-size: 1.2rem;
    margin-bottom: .3rem;
    font-weight: bold;
}

.remove-button {
    padding: 0 .8rem;
}

.add-button {
    margin-top: 20px; /* 增加添加按钮和表单之间的距离 */
}

.submit-button {
    margin-top: 20px; /* 增加提交按钮和添加按钮之间的距离 */
}

.bok-title-row {
    line-height: 24px;
}

.book-confirm-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 15px 0;
    padding: 10px 15px;
    background-color: #fff7f0;
    border: 1px solid #ffd4b3;
    border-radius: 8px;
    font-size: 12px;
}

.tip-text {
    margin-left: 8px;
    color: #ff6b35;
    line-height: 1.4;
}

</style>
